"""
标准图片处理器
"""

import time
from pathlib import Path
from typing import Dict, Any, Optional
from .ollama_client_stdlib import OllamaClient


class ImageProcessor:
    """标准图片处理器"""
    
    def __init__(self, ollama_config: Dict[str, Any], performance_config: Dict[str, Any]):
        """
        初始化图片处理器
        
        Args:
            ollama_config: Ollama配置
            performance_config: 性能配置
        """
        self.ollama_config = ollama_config
        self.performance_config = performance_config
        
        # 创建Ollama客户端
        host = f"http://{ollama_config.get('host', 'localhost')}:{ollama_config.get('port', 11434)}"
        model = ollama_config.get('model', 'qwen2.5-vl:7b')
        system_prompt = ollama_config.get('system_prompt')
        self.client = OllamaClient(host, model, system_prompt)
        
        # 性能配置
        self.delay = performance_config.get('delay', 2.0)
        self.max_retries = ollama_config.get('max_retries', 3)
        
        # 统计信息
        self.stats = {
            'total_processed': 0,
            'total_failed': 0,
            'total_time': 0,
            'avg_time': 0
        }
    
    def generate_description(self, image_path: str) -> Optional[str]:
        """
        生成图片描述
        
        Args:
            image_path: 图片文件路径
            
        Returns:
            图片描述文本
        """
        start_time = time.time()
        
        try:
            image_path = Path(image_path)
            
            # 检查文件是否存在
            if not image_path.exists():
                raise FileNotFoundError(f"图片文件不存在: {image_path}")
            
            # 分析图片
            description = self.client.analyze_image(image_path, self.max_retries)
            
            if description:
                self.stats['total_processed'] += 1
            else:
                self.stats['total_failed'] += 1
            
            # 更新统计
            processing_time = time.time() - start_time
            self.stats['total_time'] += processing_time
            self.stats['avg_time'] = self.stats['total_time'] / (self.stats['total_processed'] + self.stats['total_failed'])
            
            return description
            
        except Exception as e:
            self.stats['total_failed'] += 1
            print(f"处理图片失败: {image_path} - {e}")
            return None
    
    def get_statistics(self) -> Dict[str, Any]:
        """获取统计信息"""
        return self.stats.copy()
    
    def reset_statistics(self) -> None:
        """重置统计信息"""
        self.stats = {
            'total_processed': 0,
            'total_failed': 0,
            'total_time': 0,
            'avg_time': 0
        }